﻿using Domain.InvoiceTicket.Invoicing;
using Domain.InvoiceTicket.Ticket;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.InvoiceTicket.Invoice;
using MES.Server.API.Dto.InvoiceTicketDTO;
using ReturnValue;

namespace MES.Server.API.Application.Handler.InvoiceTicket.Invoice
{
    public class InvoiceQueryCommandHandler : IRequestHandler<InvoiceQueryCommand, ApiResult<List<InvoiceDto>>>
    {
        IRepository<InvoicingModel> invoicRep;
        IRepository<OrderModel> orderRep;
        IRepository<InvoicingorderModel> iorep;

        public InvoiceQueryCommandHandler(IRepository<InvoicingModel> invoicRep, IRepository<OrderModel> orderRep, IRepository<InvoicingorderModel> iorep)
        {
            this.iorep = iorep;
            this.orderRep = orderRep;
            this.iorep = iorep;
        }
        public Task<ApiResult<List<InvoiceDto>>> Handle(InvoiceQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<InvoiceDto>> result = new ApiResult<List<InvoiceDto>>();
            result.Code = StatusCode.Success;
            result.Message = StatusCode.Success.ToString();
            var list = from a in invoicRep.GetAll()
                       join b in iorep.GetAll() on a.Id equals b.InvoicingId
                       join c in orderRep.GetAll() on b.OrderId equals c.Id
                       where !a.IsDel
                       select new InvoiceDto
                       {
                           InvoicingCode = a.InvoicingCode,
                           InvoicingName = a.InvoicingName,
                           InvoicingType = a.InvoicingType,
                           InvoicingDate = a.InvoicingDate,
                           InvoicingMomeny = a.InvoicingMomeny,
                           ReceiveInvoicing = a.ReceiveInvoicing,
                           InvoicingDesc = a.InvoicingDesc,
                           Id = a.Id,
                           InvoicingId = b.InvoicingId,
                           OrderId = b.OrderId,
                           OrderCode = c.OrderCode,
                           OrderSon = c.OrderSon,
                           OrderState = c.OrderState,
                           OrderNum = c.OrderNum,
                           OrderGoods = c.OrderGoods,
                           ClientId = c.ClientId,
                           IsOrder = c.IsOrder,
                           IsDel = a.IsDel,
                           CreaterPeople = c.CreaterPeople,
                           CreateTime = a.CreateTime,
                           UpdaterPeople = c.UpdaterPeople,
                           UpdateTime = a.UpdateTime,


                       };
            result.Data = list.ToList();
            return Task.FromResult(result);
        }
    }
}
